﻿Xrm = window.Xrm || { __namespace: true };
Xrm.QuickNavigation = Xrm.QuickNavigation || { __namespace: true };
Xrm.QuickNavigation.ShowTab = true;
Xrm.QuickNavigation.ShowRelated = true;
Xrm.QuickNavigation.ShowCounts = true;
Xrm.QuickNavigation.ShowTabs = [];
Xrm.QuickNavigation.Relations = [];
Xrm.QuickNavigation.RelatedLinks = [];
Xrm.QuickNavigation.TabLinks = [];
Xrm.QuickNavigation.Relationships = [];
Xrm.QuickNavigation.ViewMappings = [];

$(function () {
    Xrm.QuickNavigation.GetDataParam();

    //If displaying relations - retrieve and display the contents
    if (Xrm.QuickNavigation.ShowRelated) {
        $("#RelatedLabel").show();
        $("#Related").show();
        Xrm.QuickNavigation.GetRelationships();

        // setInterval(Xrm.QuickNavigation.GetRelationships, 5000);
    }

    //If displaying tabs - retrieve and display the contents
    if (Xrm.QuickNavigation.ShowTab) {
        $("#TabsLabel").show();
        $("#Tabs").show();
        Xrm.QuickNavigation.GetTabs();
        setInterval(Xrm.QuickNavigation.GetTabs, 5000);
    }

    Xrm.QuickNavigation.LoadViewMappings();
    Xrm.QuickNavigation.GetRelationshipMetadata();
});

//Handles retrieving and displaying the links to the navigation items
Xrm.QuickNavigation.GetRelationships = function () {
    var relItems = [];

    //Add the link back to base record
    relItems.push("<li><a href='#' id='Home' title='Return to form'>Main</a></li>");

    /*
    TODO: ORDER NAVIGATION ITEMS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    */

    //Get the navigation items
    window.parent.Xrm.Page.ui.navigation.items.forEach(
        function (control) {
            //Ignore if hidden
            if (control.getVisible()) {
                //Show all navigation items if no specifc items are specified in the configuration, otherwise only show the allowed items
                if (Xrm.QuickNavigation.Relations.length === 0 || $.inArray(control.getId().toUpperCase(), Xrm.QuickNavigation.Relations) !== -1) {
                    relItems.push("<li><a href='#' id='" + control.getId() + "' class='relLink'>" + control.getLabel() + "</a></li>");
                }
            }
        }
    );

    //If there is a difference (navigation item was shown or hidden through another mechanism) rebuild the page content
    if (relItems.join("") !== Xrm.QuickNavigation.RelatedLinks.join("")) {
        $("#Related").html(relItems.join(""));
        Xrm.QuickNavigation.RelatedLinks = relItems;
    }

    //Set the click event of the link to setFocus on the navigation item
    $(".relLink").click(function () {
        var id = $(this).attr("id");
        window.parent.Xrm.Page.ui.navigation.items.forEach(
            function (control) {
                if (control.getId() === id) {
                    //Hide the tab navigation if navigating to a list of related entities
                    if (Xrm.QuickNavigation.ShowTab) {
                        $("#TabsLabel").css('visibility', 'hidden');
                        $("#Tabs").css('visibility', 'hidden');
                    }
                    control.setFocus();
                }
            }
        );
        return false;
    });

    //Set the click event for the link back to the base record
    $("#Home").click(function () {
        window.parent.window.location.replace(window.parent.document.URL);
    });
};

//Handles retrieving and displaying the links to the tabs
Xrm.QuickNavigation.GetTabs = function () {
    var tabItems = [];
    var i = 0;

    //Get the tabs
    window.parent.Xrm.Page.ui.tabs.forEach(
        function (control) {
            //Ignore if hidden
            if (control.getVisible()) {
                //Show all tabs if no specifc tabs are specified in the configuration, otherwise only show the allowed tabs
                if (Xrm.QuickNavigation.ShowTabs.length === 0 || $.inArray(control.getName().toUpperCase(), Xrm.QuickNavigation.ShowTabs) !== -1) {
                    //Tabs that are configured to not shwo the label do not return a value from getLabel() so a value is being created to show something
                    tabItems.push("<li><a href='#' id='" + control.getName() + "' class='tabLink' title='" + ((control.getLabel() === "") ? "Tab Label Not Displayed" : "") + "'>" +
                    ((control.getLabel() !== "") ? control.getLabel() : ("Tab " + i)) + "</a></li>");
                }
            }
        }
    );

    //If there is a difference (tab was shown or hidden through another mechanism) rebuild the page content
    if (tabItems.join("") !== Xrm.QuickNavigation.TabLinks.join("")) {
        $("#Tabs").html(tabItems.join(""));
        Xrm.QuickNavigation.TabLinks = tabItems;
    }

    //Set the click event of the link to setFocus on the tab
    $(".tabLink").click(function () {
        var id = $(this).attr("id");
        window.parent.Xrm.Page.ui.tabs.forEach(
            function (control) {
                if (control.getName() === id) {
                    control.setFocus();
                }
            }
        );
        return false;
    });
};

//Get the incoming data parameter
Xrm.QuickNavigation.GetDataParam = function () {
    var vals = [];
    if (location.search != "") {
        vals = location.search.substr(1).split("&");
        for (var i = 0; i < vals.length; i++) {
            vals[i] = vals[i].replace(/\+/g, " ").split("=");
        }
        for (var j = 0; j < vals.length; j++) {
            if (vals[j][0].toLowerCase() == "data") {
                Xrm.QuickNavigation.ParseData(vals[j][1]);
                break;
            }
        }
    }
};

//Parse the various parts of the incoming data parameter
//ShowTab=true
//ShowRelated=true
//ShowCounts=true
//Tabs=tabName1,tabName2
//Relations=navId1,navId2
Xrm.QuickNavigation.ParseData = function (data) {
    var vals = [];
    vals = decodeURIComponent(data).split("&");
    for (var i = 0; i < vals.length; i++) {
        vals[i] = vals[i].replace(/\+/g, " ").split("=");
    }

    for (var x = 0; x < vals.length; x++) {
        switch (vals[x][0].toUpperCase()) {
            case "SHOWTAB":
                Xrm.QuickNavigation.ShowTab = (vals[x][1].toUpperCase() === "TRUE") ? true : false;
                break;
            case "SHOWRELATED":
                Xrm.QuickNavigation.ShowRelated = (vals[x][1].toUpperCase() === "TRUE") ? true : false;
                break;
            case "SHOWCOUNTS":
                Xrm.QuickNavigation.ShowCounts = (vals[x][1].toUpperCase() === "TRUE") ? true : false;
                break;
            case "TABS":
                Xrm.QuickNavigation.ShowTabs = vals[x][1].toUpperCase().split(",");
                break;
            case "RELATIONS":
                Xrm.QuickNavigation.Relations = vals[x][1].toUpperCase().split(",");
                break;
        }
    }
};

Xrm.QuickNavigation.GetRelationshipMetadata = function () {
    var mdq = SDK.Metadata.Query;
    var semp = mdq.SearchableEntityMetadataProperties;
    var samp = mdq.SearchableAttributeMetadataProperties;
    var emp = mdq.EntityMetadataProperties;
    var rmp = mdq.RelationshipMetadataProperties;

    var entityFilter = new mdq.MetadataFilterExpression(mdq.LogicalOperator.And);
    entityFilter.addCondition(semp.LogicalName, mdq.MetadataConditionOperator.Equals, window.parent.Xrm.Page.data.entity.getEntityName());
    var entityProperties = new mdq.MetadataPropertiesExpression(false, [emp.ManyToManyRelationships, emp.OneToManyRelationships, emp.ManyToOneRelationships]);
    var relationshipFilter = new mdq.MetadataFilterExpression(mdq.LogicalOperator.And);
    relationshipFilter.addCondition(samp.IsValidForAdvancedFind, mdq.MetadataConditionOperator.Equals, true);
    var relationshipProperties = new mdq.MetadataPropertiesExpression(true, [rmp.ManyToManyRelationships, rmp.OneToManyRelationships, rmp.ManyToOneRelationships]);

    var labelQuery = new mdq.LabelQueryExpression([window.parent.Xrm.Page.context.getUserLcid()]);
    var query = new mdq.EntityQueryExpression(
        entityFilter,
        entityProperties,
        null,
        new mdq.RelationshipQueryExpression(relationshipFilter, relationshipProperties),
        labelQuery);
    var request = new mdq.RetrieveMetadataChangesRequest(query);
    mdq.RetrieveMetadataChanges(
        request,
        function (entityMetadata) {
            for (var h = 0; h < entityMetadata.EntityMetadata[0].ManyToOneRelationships.length; h++) {
                var mtoRelationship = {};
                mtoRelationship.SchemaName = entityMetadata.EntityMetadata[0].ManyToOneRelationships[h].SchemaName;
                mtoRelationship.ReferencedAttribute = entityMetadata.EntityMetadata[0].ManyToOneRelationships[h].ReferencedAttribute;
                mtoRelationship.ReferencedEntity = entityMetadata.EntityMetadata[0].ManyToOneRelationships[h].ReferencedEntity;
                mtoRelationship.Type = "N:1";
                Xrm.QuickNavigation.Relationships.push(mtoRelationship);
            }

            for (var i = 0; i < entityMetadata.EntityMetadata[0].OneToManyRelationships.length; i++) {
                var otmRelationship = {};
                otmRelationship.SchemaName = entityMetadata.EntityMetadata[0].OneToManyRelationships[i].SchemaName;
                otmRelationship.ReferencingAttribute = entityMetadata.EntityMetadata[0].OneToManyRelationships[i].ReferencingAttribute;
                otmRelationship.ReferencingEntity = entityMetadata.EntityMetadata[0].OneToManyRelationships[i].ReferencingEntity;
                otmRelationship.Type = "1:N";
                Xrm.QuickNavigation.Relationships.push(otmRelationship);
            }

            for (var j = 0; j < entityMetadata.EntityMetadata[0].ManyToManyRelationships.length; j++) {
                var mtmRelationship = {};
                mtmRelationship.SchemaName = entityMetadata.EntityMetadata[0].ManyToManyRelationships[j].SchemaName;
                mtmRelationship.IntersectEntityName = entityMetadata.EntityMetadata[0].ManyToManyRelationships[j].IntersectEntityName;
                mtmRelationship.Entity1LogicalName = entityMetadata.EntityMetadata[0].ManyToManyRelationships[j].Entity1LogicalName;
                mtmRelationship.Entity1IntersectAttribute = entityMetadata.EntityMetadata[0].ManyToManyRelationships[j].Entity1IntersectAttribute;
                mtmRelationship.Entity2LogicalName = entityMetadata.EntityMetadata[0].ManyToManyRelationships[j].Entity2LogicalName;
                mtmRelationship.Entity2IntersectAttribute = entityMetadata.EntityMetadata[0].ManyToManyRelationships[j].Entity2IntersectAttribute;
                mtmRelationship.Type = "N:N";
                Xrm.QuickNavigation.Relationships.push(mtmRelationship);
            }

            Xrm.QuickNavigation.GetFormXML();
        },
        function (error) {
            console.log(error.message);
        });
};

Xrm.QuickNavigation.LoadViewMappings = function () {
    $.get(
        "xml/Xrm.QuickNavigation.ViewMap.xml",
        function (data) {
            for (var i = 0; i < $(data).find("Item").length; i++) {
                var mapping = {};
                mapping.Entity = $($(data).find("Item")[i]).attr("entity");
                mapping.RelationshipName = $($(data).find("Item")[i]).attr("relationshipname");
                mapping.Id = $($(data).find("Item")[i]).attr("id");
                if (mapping.RelationshipName === "*FETCHXML*") {
                    var fetchXml = $($(data).find("Item")[i]).text().trim();
                    fetchXml = fetchXml.replace("*REPLACEID*", window.parent.Xrm.Page.data.entity.getId());
                    mapping.FetchXML = $.parseXML(fetchXml);
                } else {
                    mapping.ViewId = $($(data).find("Item")[i]).text();
                }
                mapping.Type = $($(data).find("Item")[i]).attr("type");
                Xrm.QuickNavigation.ViewMappings.push(mapping);
            }
        }
    );
};

Xrm.QuickNavigation.GetAssociatedViewFetchXML = function (navId, relationshipName, entity, type) {
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        datatype: 'json',
        url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/SavedQuerySet?$select=FetchXml,IsDefault&$filter=QueryType eq 2 and ReturnedTypeCode eq '" +
            entity + "' and FetchXml ne null",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('Accept', 'application/json');
        },
        async: true,
        success: function (data, textStatus, xhr) {
            var results = data.d.results;
            for (var i = 0; i < results.length; i++) {
                if (results[i].IsDefault) {
                    var fetchXml = results[i].FetchXml;
                    if (fetchXml !== null && fetchXml !== undefined) {
                        Xrm.QuickNavigation.ProcessFetchXML(fetchXml, navId, relationshipName, type);
                    }
                }
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + ' ' + errorThrown);
        }
    });
};

Xrm.QuickNavigation.GetMappedViewId = function (viewId, navId, relationshipName, type) {
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        datatype: 'json',
        url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/SavedQuerySet(guid'" + viewId + "')?$select=FetchXml&undefined",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('Accept', 'application/json');
        },
        async: true,
        success: function (data, textStatus, xhr) {
            var result = data.d;
            var fetchXml = result.FetchXml;
            if (fetchXml !== null && fetchXml !== undefined) {
                Xrm.QuickNavigation.ProcessFetchXML(fetchXml, navId, relationshipName, type);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + ' ' + errorThrown);
        }
    });
};

Xrm.QuickNavigation.ProcessFetchXML = function (fetchXml, navId, relationshipName, type) {
    fetchXml = $.parseXML(fetchXml);
    $(fetchXml).find("order").remove();
    $(fetchXml).find("attribute").remove();
    $(fetchXml).find("fetch").attr("aggregate", "true");

    var relationships = $.grep(Xrm.QuickNavigation.Relationships, function (e) { return e.SchemaName === relationshipName && e.Type === type; });
    if (relationships.length === 1) {
        if (relationships[0].Type === "1:N") {
            fetchXml = Xrm.QuickNavigation.CheckStateCode(fetchXml, relationships[0].ReferencingEntity);
            $(fetchXml).find("entity").append("<attribute name='" + relationships[0].ReferencingAttribute + "' alias='count' aggregate='count' />");
            var filter = $(fetchXml).find("filter");
            if (filter.length === 1) {
                $(filter).append("<condition attribute='" + relationships[0].ReferencingAttribute + "' operator='eq' value='" + window.parent.Xrm.Page.data.entity.getId() + "' />");
            } else {
                $(fetchXml).find("entity").append("<filter type='and'><condition attribute='" + relationships[0].ReferencingAttribute + "' operator='eq' value='" + window.parent.Xrm.Page.data.entity.getId() + "' /></filter>");
            }
            $(fetchXml).find("entity").attr("name", relationships[0].ReferencingEntity);
        } else if (relationships[0].Type === "N:N") {
            var link = [];
            if (relationships[0].Entity1LogicalName === window.parent.Xrm.Page.data.entity.getEntityName()) {
                $(fetchXml).find("entity").attr("name", relationships[0].Entity2LogicalName);
                $(fetchXml).find("entity").append("<attribute name='" + relationships[0].Entity2IntersectAttribute + "' alias='count' aggregate='count' />");
                link.push("<link-entity name='" + relationships[0].IntersectEntityName + "' to='" + relationships[0].Entity2IntersectAttribute + "' from='" + relationships[0].Entity2IntersectAttribute + "' link-type='inner'>");
                link.push("<link-entity name='" + relationships[0].Entity1LogicalName + "' to='" + relationships[0].Entity1IntersectAttribute + "' from='" + relationships[0].Entity1LogicalName + "id' link-type='inner'>");
                link.push("<filter type='and'>");
                link.push("<condition attribute='" + relationships[0].Entity1LogicalName + "id' operator='eq' value='" + window.parent.Xrm.Page.data.entity.getId() + "' />");
            } else {
                $(fetchXml).find("entity").attr("name", relationships[0].Entity1LogicalName);
                $(fetchXml).find("entity").append("<attribute name='" + relationships[0].Entity1IntersectAttribute + "' alias='count' aggregate='count' />");
                link.push("<link-entity name='" + relationships[0].IntersectEntityName + "' to='" + relationships[0].Entity1IntersectAttribute + "' from='" + relationships[0].Entity1IntersectAttribute + "' link-type='inner'>");
                link.push("<link-entity name='" + relationships[0].Entity2LogicalName + "' to='" + relationships[0].Entity2IntersectAttribute + "' from='" + relationships[0].Entity2LogicalName + "id' link-type='inner'>");
                link.push("<filter type='and'>");
                link.push("<condition attribute='" + relationships[0].Entity2LogicalName + "id' operator='eq' value='" + window.parent.Xrm.Page.data.entity.getId() + "' />");
            }
            link.push("</filter>");
            link.push("</link-entity>");
            link.push("</link-entity>");
            $(fetchXml).find("entity").append(link.join(""));

            var entityToReplace = ["listaccount_association", "listcontact_association", "listlead_association", "campaignsalesliterature_association", "campaignproduct_association",
                "campaigncampaign_association", "campaignlist_association"];

            //Replace entityid with the specific entity name + id
            if ($.inArray(relationshipName, entityToReplace) !== -1) {
                if (relationships[0].Entity1LogicalName === window.parent.Xrm.Page.data.entity.getEntityName()) {
                    $(fetchXml).find("attribute").attr("name", relationships[0].Entity2LogicalName + "id");
                    $(fetchXml).find("link-entity:first").attr("to", relationships[0].Entity2LogicalName + "id");
                } else {
                    $(fetchXml).find("attribute").attr("name", relationships[0].Entity1LogicalName + "id");
                    $(fetchXml).find("link-entity:first").attr("to", relationships[0].Entity1LogicalName + "id");
                }
            }
        }
        else if (relationships[0].Type === "N:1") {
            fetchXml = Xrm.QuickNavigation.CheckStateCode(fetchXml, relationships[0].ReferencedEntity);
            $(fetchXml).find("entity").append("<attribute name='" + relationships[0].ReferencedAttribute + "' alias='count' aggregate='count' />");
            var filter = $(fetchXml).find("filter");
            if (filter.length === 1) {
                $(filter).append("<condition attribute='" + relationships[0].ReferencedAttribute + "' operator='eq' value='" + window.parent.Xrm.Page.data.entity.getId() + "' />");
            } else {
                $(fetchXml).find("entity").append("<filter type='and'><condition attribute='" + relationships[0].ReferencedAttribute + "' operator='eq' value='" + window.parent.Xrm.Page.data.entity.getId() + "' /></filter>");
            }
            $(fetchXml).find("entity").attr("name", relationships[0].ReferencedEntity);
        }
    }

    Xrm.QuickNavigation.GetRecordCounts(fetchXml, navId);
};

Xrm.QuickNavigation.CheckStateCode = function (fetchXml, entity) {
    var noState = ["customerrelationship", "customeraddress"];
    var matches = $.grep(noState, function (e) { return e === entity; });
    if (matches.length > 0) {
        $(fetchXml).find("condition[attribute='statecode']").remove();
    }
    return fetchXml;
};

Xrm.QuickNavigation.GetRecordCounts = function (fetchXml, navId) {
    var xml = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"><request i:type="b:RetrieveMultipleRequest" xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic"> <b:KeyValuePairOfstringanyType><c:key>Query</c:key><c:value i:type="b:FetchExpression"><b:Query>';
    var serializer = new XMLSerializer();
    xml += CrmEncodeDecode.CrmXmlEncode(serializer.serializeToString(fetchXml));
    xml += '</b:Query></c:value></b:KeyValuePairOfstringanyType></b:Parameters><b:RequestId i:nil="true"/><b:RequestName>RetrieveMultiple</b:RequestName></request></Execute></s:Body></s:Envelope>';

    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", true);
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    req.onreadystatechange = function () {
        if (req.readyState === 4) {
            var count = "";

            //Check for 50000+ aggregate limit
            if (req.status === 500) {
                var fault = $(req.responseXML).find("s\\:Fault, Fault");
                if (fault.length > 0) {
                    var errorCode = $(fault).find("OrganizationServiceFault").find("ErrorCode:first").text();
                    if (errorCode === "-2147164125") {
                        count = "50000+";
                    }
                }
            } else if (req.status === 200) {
                var results = $(req.responseXML).find("a\\:Results, Results");
                if (results.length > 0) {
                    count = $(results).find("a\\:FormattedValues, FormattedValues").find("a\\:KeyValuePairOfstringstring, KeyValuePairOfstringstring").find("b\\:value, value").text();
                }
            }

            $("#" + navId).text($("#" + navId).text() + " (" + count + ")");
        }
    };
    req.send(xml);
};

Xrm.QuickNavigation.GetFormXML = function () {
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        datatype: 'json',
        url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/SystemFormSet(guid'" + window.parent.Xrm.Page.ui.formSelector.getCurrentItem().getId() + "')?$select=FormXml",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('Accept', 'application/json');
        },
        async: true,
        success: function (data, textStatus, xhr) {
            var result = data.d;
            var formXml = result.FormXml;
            var relationshipItems = $(formXml).find("NavBarByRelationshipItem");
            for (var i = 0; i < relationshipItems.length; i++) {
                var viewIds = $.grep(Xrm.QuickNavigation.ViewMappings, function (e) {
                    return (e.Entity === window.parent.Xrm.Page.data.entity.getEntityName() && e.Id === $(relationshipItems[i]).attr("id"));
                });

                if (viewIds.length > 0) {
                    if ($(relationshipItems[i]).attr("show") !== "false") {
                        if (viewIds[0].FetchXML !== undefined) { //Pre-defined FetchXML
                            Xrm.QuickNavigation.GetRecordCounts(viewIds[0].FetchXML, viewIds[0].Id);
                        } else {
                            for (var x = 0; x < viewIds.length; x++) { //Loop through all possible results, normally should be 1 but Marketing List could have multiple depending on entity type
                                if (window.parent.Xrm.Page.data.entity.getEntityName() === "list" && viewIds[x].RelationshipName.match("^list") && viewIds[x].RelationshipName.match("_association$")) { //but only process the one related to the current list type
                                    if (viewIds[x].RelationshipName !== "list" + window.parent.Xrm.Page.getAttribute("createdfromcode").getText().toLowerCase() + "_association") continue;
                                }
                                Xrm.QuickNavigation.GetMappedViewId(viewIds[x].ViewId, viewIds[x].Id, viewIds[x].RelationshipName, viewIds[x].Type);
                            }
                        }
                    }
                } else {
                    if ($(relationshipItems[i]).attr("show") !== "false") {
                        var relationships = $.grep(Xrm.QuickNavigation.Relationships, function (e) { return e.SchemaName === $(relationshipItems[i]).attr("relationshipname") && e.Type !== "N:1"; });
                        if (relationships.length === 1) {
                            if (relationships[0].Type === "1:N") {
                                Xrm.QuickNavigation.GetAssociatedViewFetchXML($(relationshipItems[i]).attr("id"), $(relationshipItems[i]).attr("relationshipname"), relationships[0].ReferencingEntity, relationships[0].Type);
                            } else {
                                Xrm.QuickNavigation.GetAssociatedViewFetchXML($(relationshipItems[i]).attr("id"), $(relationshipItems[i]).attr("relationshipname"),
                                   (relationships[0].Entity1LogicalName === window.parent.Xrm.Page.data.entity.getEntityName()) ? relationships[0].Entity2LogicalName : relationships[0].Entity1LogicalName, relationships[0].Type);
                            }
                        }
                    }
                }
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log(textStatus + ' ' + errorThrown);
        }
    });
};